package com.tedu.egspringbootmvc.controller;

import com.tedu.egspringbootmvc.mapper.IArticleMapper;
import com.tedu.egspringbootmvc.mapper.IUserMapper;
import com.tedu.egspringbootmvc.pojo.dto.UserArticleDTO;
import com.tedu.egspringbootmvc.pojo.dto.UserLoginDTO;
import com.tedu.egspringbootmvc.pojo.entity.Article;
import com.tedu.egspringbootmvc.pojo.vo.ArticleVO;
import com.tedu.egspringbootmvc.pojo.vo.UserVO;
import com.tedu.egspringbootmvc.result.JsonResult;
import com.tedu.egspringbootmvc.result.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/v1/users")
@Slf4j
@Api(tags = "用户文章模块")
public class UserController {
    @Autowired
    private IUserMapper iUserMapper;
    @Autowired
    private IArticleMapper iArticleMapper;

    @PostMapping("/login")
    @ApiOperation("登录")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("userLoginDTO"+userLoginDTO);

        UserVO userVO = iUserMapper.login(userLoginDTO);
        if(userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.success();

    }

    @PostMapping("/article")
    @ApiOperation("发布文章")
    public JsonResult upload(@RequestBody @Validated UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        log.debug("userArticleDTO"+userArticleDTO);
        UserVO userVO = (UserVO)session.getAttribute("user");
        /*UserVO userVO = (UserVO)session.getAttribute("user");
        if(userVO==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }*/
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        iArticleMapper.insert(article);
        return JsonResult.success();
    }

    @GetMapping("/selectByArticleId")
    @ApiOperation("查看某一篇文章")
    @ApiImplicitParam(value = "微博id",required = true,type = "Integer",example = "1")
    public JsonResult selectByArticleId(@Range(min = 1,max = 999999,message = "微博id在1-999999之间") Integer id){
        ArticleVO articleVO = iArticleMapper.selectById(id);
        return JsonResult.success(articleVO);

    }

}
